<template>
    <div class="comment-item">
        <div class="comment-header">
            <el-avatar :src="comment.user.profile_photo_path" shape="circle" :size="30" style="margin-right: 10px"></el-avatar>
            <div class="comment-info">
                <span class="username">{{ comment.user.username }}</span>
                <span class="time">{{ comment.created_at }}</span>
            </div>
        </div>
        <p class="content" v-html="comment.content"></p>
        <div class="comment-actions">
            <span @click="openReplyBox(comment.commentId)">回复</span>
            <span v-if="comment.children && comment.children.length > 0" @click="toggleChildren">
                {{ showChildren ? '收起回复' : '查看回复' }} ({{ comment.children.length }})
            </span>
        </div>
        <!-- 回复框（使用插槽方式，更灵活） -->
        <div v-if="replyCommentId === comment.commentId">
            <TextEditor
                ref="editorRef"
                placeholder="写下你的回复..."
                @getContent="handleGetContent"
            />
            <div class="reply-actions">
                <el-button size="small" type="primary" @click="submitReply">提交回复</el-button>
                <el-button size="small" @click="cancelReply">取消</el-button>
            </div>
        </div>
        <div v-if="showChildren && comment.children && comment.children.length > 0" class="children-comments">
            <CommentItem
                v-for="childComment in comment.children"
                :key="childComment.commentId"
                :comment="childComment"
                :depth="depth + 1"
                @reply="openReplyBox"
                @addReply="addNewReply"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, watch, nextTick, reactive } from 'vue';
import TextEditor from "@/components/TextEditor.vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";

//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}

const emit = defineEmits(['reply', 'addReply']);

const props = defineProps({
    comment: {
        type: Object,
        required: true
    },
    depth: {
        type: Number,
        default: 0
    }
});

const showChildren = ref(false);
const replyCommentId = ref(null);  // 当前正在回复的评论ID
const replyContent = ref('');      // 回复内容
const editorRef = ref();       // 编辑器引用
const isLoading = ref(false);      // 提交加载状态
// 打开回复框
const openReplyBox = (commentId) => {
    // 如果点击的是当前已打开的回复框，则关闭
    if (replyCommentId.value === commentId) {
        cancelReply();
        return;
    }
    // 否则打开新的回复框
    replyCommentId.value = commentId;
    replyContent.value = '';
    // 如果是折叠状态，则展开
    if (!showChildren.value) {
        showChildren.value = true;
    }
};
// 取消回复
const cancelReply = () => {
    replyCommentId.value = null;
    replyContent.value = '';
};
// 获取编辑器内容
const handleGetContent = (content) => {
    replyContent.value = content;
};
// 提交回复
const submitReply = async () => {
    await nextTick(); // 确保 DOM 更新后再调用 exposeContent
    if (editorRef.value) {
        editorRef.value.exposeContent();
    }
    // 验证内容
    if (!replyContent.value) {
        ElMessage.warning('回复内容不能为空');
        return;
    }
    // 显示加载状态
    isLoading.value = true;
    try {
        // 数据
        const newReply = {
            userId: user.user_id, // 当前登录用户ID
            targetId: props.comment.targetId,
            targetType: 'COMMENT',
            parentId: props.comment.commentId,
            content: replyContent.value,
        };
        // 通知父组件添加新回复
        emit('addReply', newReply);
        // 清空回复框并关闭
        cancelReply();
    } catch (error) {
        ElMessage.error('回复失败，请重试');
        console.error('提交回复失败:', error);
    } finally {
        isLoading.value = false;
    }
};
// 切换子评论显示状态
const toggleChildren = () => {
    showChildren.value = !showChildren.value;
};
// 添加新回复到评论列表
const addNewReply = (newReply) => {
    request.post('/api/comment/addComment', newReply).then(res => {
        if (res.code === '200') {
            ElMessage.success("回复成功")
            location.reload()
        } else {
            ElMessage.error("回复未发送")
        }
    })
};
// 监听props变化，确保数据更新
watch(() => props.comment, (newComment) => {
    // 如果评论数据更新，检查是否需要更新子评论列表
    if (newComment.children) {
        // 可以在这里添加额外的数据处理逻辑
    }
});
</script>

<style scoped>
.comment-item {
    border-bottom: 1px solid #cccbc8;
    padding: 10px;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.comment-info {
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: bold;
    margin-bottom: 5px;
}

.time {
    color: #999;
    font-size: 12px;
}

.content {
    margin-bottom: 10px;
}
::v-deep .content img {  /*深度选择器 ::v-deep 来穿透作用域,用来选择使用v-html插入的元素*/
    width: auto;
    height: 300px;
    display: flex;
    margin: 0 auto;
}

.comment-actions {
    display: flex;
    font-size: 12px;
    color: #666;
}

.comment-actions span {
    cursor: pointer;
    margin-right: 15px;
}

.children-comments {
    margin-left: 30px;
    margin-top: 10px;
    padding-left: 20px;
    border-left: 1px solid #eaeaea;
}
</style>